package com.gct.security;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.crypto.keygen.KeyGenerators;

import com.aliyuncs.utils.Base64Helper;

public class HttpURLSecurity {
    private static Logger logger = LoggerFactory.getLogger(HttpURLSecurity.class);
    private final static String password;
    private final static String content;
    private final static String salt;
    private final static TextEncryptor encryptor;

    static {
        Properties prop = new Properties();
        InputStream ins = HttpURLSecurity.class.getResourceAsStream("securityprop.properties");
        try {
            prop.load(ins);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        password = prop.getProperty("password");
        content = prop.getProperty("content");
        salt = prop.getProperty("salt");
        encryptor = Encryptors.text(password, salt);
    }
    private static String encryptInternal() {
        String encryptedText = encryptor.encrypt(content);
        return encryptedText;
    }

    public static String decryptInternal(String encryptedText) {
        String decryptedText = encryptor.decrypt(encryptedText);
        return decryptedText;
    }

    public static String encrypt() {
        try {
            return Base64Helper.encode(encryptInternal(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encrypt(String textToEncrypt) {
        try {
            return Base64Helper.encode(encryptor.encrypt(textToEncrypt), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static boolean decrypt(String encryptedText) {
        try {
            String decryptedText = decryptInternal(Base64Helper.decode(encryptedText, "utf-8"));
//            logger.info(decryptedText);
            if(content.equals(decryptedText))
                return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /*
     * only for regenerate Salt.
     */
    @SuppressWarnings("unused")
    private static String generateSalt() {
        return KeyGenerators.string().generateKey();
    }

    @Test
    public void testA() {
        logger.info(encrypt());
        HttpURLSecurity.decrypt(encrypt());
    }
}
